package com.springboot.config.security.wx;

import com.springboot.config.security.JwtConfig;
import com.springboot.entity.WxUser;
import com.springboot.enums.ErrorEnum;
import com.springboot.exception.MyException;
import com.springboot.utils.UserUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @descrition: 小程序用户过滤器
 * @author: lzh
 */
@Component
public class WxUserAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtConfig jwtConfig;

    @Autowired
    WxUserDetailsService wxUserDetailsService;

    private final String LOGIN = "/wx/login";

    private final String REGISTER = "/wx/register";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = request.getHeader(jwtConfig.getHeader());
        response.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        if(!uri.startsWith("/wx/") || uri.endsWith(LOGIN) || uri.endsWith(REGISTER)) {
            filterChain.doFilter(request, response);
            return ;
        }
        //token验证
        Claims claims = null;
        try{
            claims = jwtConfig.getTokenClaim(token, true);
        } catch (Exception e) {
            throw new MyException(ErrorEnum.TOKEN_INVALID);
        }
        if(jwtConfig.isTokenExpired(claims.getExpiration())) {
            throw new MyException(ErrorEnum.TOEKN_EXPIRED);
        }
        //添加认证用户信息
        UserDetails userDetails = wxUserDetailsService.loadUserByUsername(claims.getSubject());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        usernamePasswordAuthenticationToken.setDetails(
                new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);
    }
}
